//
//  UITableViewCell+MLKit.m
//
//  Created by molon on 15/6/18.
//  Copyright (c) 2015年 molon. All rights reserved.
//

#import "UITableViewCell+MLKit.h"

@implementation UITableViewCell (MLKit)

+ (UINib *)nib
{
    return [UINib nibWithNibName:NSStringFromClass([self class]) bundle:[NSBundle mainBundle]];
}

+ (instancetype)instanceFromNib
{
    return [[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil]lastObject];
}

+ (NSString *)cellReuseIdentifier
{
    return NSStringFromClass([self class]);
}

+ (CGFloat)heightForObject:(id)object maxWidth:(CGFloat)maxWidth
{
//    [self doesNotRecognizeSelector:_cmd];
    
    return 44.0f;
}


- (void)temporaryCancelReuse:(BOOL)cancelReuse
{
    if (cancelReuse) {
        NSString *temporarilyReuseIdentifier = [NSString stringWithFormat:@"%@%p",[[self class]cellReuseIdentifier],self];
        [self setValue:temporarilyReuseIdentifier forKey:@"reuseIdentifier"];
    }else{
        [self setValue:[[self class]cellReuseIdentifier] forKey:@"reuseIdentifier"];
    }
}


- (CGFloat)autolayoutFitHeightWithMaxWidth:(CGFloat)maxWidth doAfterReuseBlock:(void(^)())doAfterReuseBlock
{
    [self prepareForReuse];
    
    if (doAfterReuseBlock) {
        doAfterReuseBlock();
    }
    
    if (![self.contentView respondsToSelector:@selector(systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority:)]) {
        NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeWidth multiplier:1.0f constant:maxWidth];
        constraint.priority = 999;
        [self.contentView addConstraint:constraint];
        
        CGSize size = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        
        [self.contentView removeConstraint:constraint];
        
        return size.height+1.0f;
    }
    
    CGSize fittingSize = UILayoutFittingCompressedSize;
    fittingSize.width = maxWidth;
    CGSize size = [self.contentView systemLayoutSizeFittingSize:fittingSize withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityDefaultLow];
    
    return size.height+1.0f;
}

@end
